<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket实时通信测试</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 10px 0;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .message {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            margin: 5px 0;
        }
        .message-header {
            font-weight: bold;
            color: #495057;
        }
        .message-content {
            margin: 5px 0;
            color: #6c757d;
        }
        .message-time {
            font-size: 0.8em;
            color: #adb5bd;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            margin: 5px 0;
        }
        .form-group {
            margin: 10px 0;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>WebSocket实时通信测试</h1>
    
    <div class="container">
        <h3>连接状态</h3>
        <div id="status" class="status disconnected">未连接</div>
        <div>
            <label for="token">JWT Token:</label>
            <input type="text" id="token" placeholder="请输入JWT Token">
        </div>
        <button id="connectBtn" onclick="connect()">连接</button>
        <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
    </div>

    <div class="container">
        <h3>消息发送</h3>
        <div class="form-group">
            <label for="messageType">消息类型:</label>
            <select id="messageType">
                <option value="ping">心跳检测</option>
                <option value="status">状态更新</option>
                <option value="error">错误消息</option>
            </select>
        </div>
        <div class="form-group">
            <label for="messageContent">消息内容:</label>
            <textarea id="messageContent" rows="3" placeholder="请输入消息内容"></textarea>
        </div>
        <button onclick="sendMessage()">发送消息</button>
    </div>

    <div class="container">
        <h3>接收到的消息</h3>
        <div id="messages"></div>
        <button onclick="clearMessages()">清空消息</button>
    </div>

    <script>
        let stompClient = null;
        let isConnected = false;

        function connect() {
            const token = document.getElementById('token').value;
            if (!token) {
                alert('请输入JWT Token');
                return;
            }

            // 创建SockJS连接
            const socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);

            // 设置认证头
            const headers = {
                'Authorization': 'Bearer ' + token
            };

            stompClient.connect(headers, function(frame) {
                console.log('连接成功: ' + frame);
                isConnected = true;
                updateStatus('已连接', 'connected');
                
                // 启用/禁用按钮
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;

                // 订阅用户专用消息队列
                stompClient.subscribe('/user/queue/messages', function(message) {
                    const messageData = JSON.parse(message.body);
                    displayMessage('用户消息', messageData);
                });

                // 订阅广播消息
                stompClient.subscribe('/topic/broadcast', function(message) {
                    const messageData = JSON.parse(message.body);
                    displayMessage('广播消息', messageData);
                });

                // 订阅心跳响应
                stompClient.subscribe('/user/queue/pong', function(message) {
                    const messageData = JSON.parse(message.body);
                    displayMessage('心跳响应', messageData);
                });

                // 订阅状态更新响应
                stompClient.subscribe('/user/queue/status', function(message) {
                    const messageData = JSON.parse(message.body);
                    displayMessage('状态更新', messageData);
                });

                // 订阅错误消息
                stompClient.subscribe('/user/queue/error', function(message) {
                    const messageData = JSON.parse(message.body);
                    displayMessage('错误消息', messageData);
                });

            }, function(error) {
                console.log('连接失败: ' + error);
                updateStatus('连接失败: ' + error, 'disconnected');
                isConnected = false;
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
                stompClient = null;
            }
            isConnected = false;
            updateStatus('已断开连接', 'disconnected');
            
            // 启用/禁用按钮
            document.getElementById('connectBtn').disabled = false;
            document.getElementById('disconnectBtn').disabled = true;
        }

        function sendMessage() {
            if (!isConnected) {
                alert('请先连接WebSocket');
                return;
            }

            const messageType = document.getElementById('messageType').value;
            const messageContent = document.getElementById('messageContent').value;

            if (!messageContent) {
                alert('请输入消息内容');
                return;
            }

            const message = {
                type: messageType,
                content: messageContent,
                timestamp: new Date().toISOString()
            };

            stompClient.send('/app/' + messageType, {}, JSON.stringify(message));
            
            // 清空输入框
            document.getElementById('messageContent').value = '';
        }

        function displayMessage(type, messageData) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message';
            
            const headerDiv = document.createElement('div');
            headerDiv.className = 'message-header';
            headerDiv.textContent = type + ' - ' + messageData.title;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = messageData.content;
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = new Date(messageData.timestamp).toLocaleString();
            
            messageDiv.appendChild(headerDiv);
            messageDiv.appendChild(contentDiv);
            messageDiv.appendChild(timeDiv);
            
            messagesDiv.insertBefore(messageDiv, messagesDiv.firstChild);
        }

        function updateStatus(text, className) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = text;
            statusDiv.className = 'status ' + className;
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
        }

        // 页面加载时自动连接（如果有token）
        window.onload = function() {
            const token = localStorage.getItem('jwt_token');
            if (token) {
                document.getElementById('token').value = token;
            }
        };

        // 保存token到本地存储
        document.getElementById('token').addEventListener('change', function() {
            localStorage.setItem('jwt_token', this.value);
        });
    </script>
</body>
</html>
